import {getGoods, getNewGoods, getRecommend, searchByName} from '@/services/backend/generatorController';
import {PageContainer} from '@ant-design/pro-components';
import {Card, Flex, FloatButton, Image, Input, List, message, Tabs, Tag, Typography} from 'antd';
import moment from 'moment';
import React, {useEffect, useState} from 'react';
import {Link} from 'umi';
import {CommentOutlined} from "@ant-design/icons";
import {useModel} from "@@/exports";

/**
 * 默认分页参数
 */
const DEFAULT_PAGE_PARAMS: PageRequest = {
  current: 1,
  pageSize: 12,
  sortField: 'createTime',
  sortOrder: 'descend',
};

/**
 * 主页
 * @constructor
 */
const IndexPage: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(true);
  const [dataList, setDataList] = useState<API.GoodsResult[]>([]);
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState ?? {};
  const myId=currentUser?.id;

  /**
   * 搜索
   */
  const doSearch = async (classify:string) => {
    setLoading(true);
    try {
      if(classify==="recommend"){
        const res = await getRecommend(myId as number);
        setDataList(res ?? []);
      }else if(classify==="all"){
        const res = await getGoods(myId as number);
        setDataList(res ?? []);
      }else if(classify==="newest"){
        const res = await getNewGoods(myId as number);
        setDataList(res ?? []);
      }
    } catch (error: any) {
      message.error('获取数据失败，' + error.message);
    }
    setLoading(false);
  };

  useEffect(() => {
    doSearch("all");
  }, [1]);

  /**
   * 搜索
   */
  const searchGoods=async (name:string)=>{
    setLoading(true);
    try{
      const res = await searchByName(name);
      setDataList(res ?? []);
    } catch (error: any) {
    message.error('获取数据失败，' + error.message);
    }
    setLoading(false);
  }

  /**
   * 标签列表
   * @param tags
   */
  const tagListView = (tag?: string) => {
    if (!tag) {
      return <></>;
    }

    return (
      <div style={{ marginBottom: 8 }}>
          <Tag key={tag}>{tag}</Tag>
      </div>
    );
  };

  return (
    <PageContainer title={<></>}>
      <Flex justify="center">
        <Input.Search
          style={{
            width: '40vw',
            minWidth: 320,
          }}
          placeholder="搜索商品"
          allowClear
          enterButton="搜索"
          size="large"
          // onChange={(e) => {
          //   searchParams.searchText = e.target.value;
          // }}
          onSearch={(value: string) => {
            // setSearchParams({
            //   ...searchParams,
            //   ...DEFAULT_PAGE_PARAMS,
            //   searchText: value,
            // });
            searchGoods(value);
          }}
        />
      </Flex>
      <div style={{ marginBottom: 16 }} />

      <Tabs
        size="large"
        defaultActiveKey="all"
        items={[
          {
            key: 'all',
            label: '全部',
          },
          {
            key: 'newest',
            label: '最新',
          },
          {
            key: 'recommend',
            label: '推荐',
          },
        ]}
        onChange={(activeKey) => {
            doSearch(activeKey);
          }
        }
      />

      <div style={{ marginBottom: 24 }} />

      <List<API.GoodsResult>
        rowKey="id"
        loading={loading}
        grid={{
          gutter: 16,
          xs: 1,
          sm: 2,
          md: 3,
          lg: 3,
          xl: 4,
          xxl: 4,
        }}
        dataSource={dataList}
        pagination={{
          defaultPageSize:8,
        }}
        renderItem={(data) => (
          <List.Item>
            <Link to={`/generator/detail/${data.id}`}>
              <Card hoverable cover={<Image height={350} alt={data.goodsName} src={data.goodsImage} />}>
                <Card.Meta
                  title={<a>{data.goodsName}</a>}
                  description={
                    <Typography.Paragraph ellipsis={{ rows: 2 }} style={{ height: 44 }}>
                      {data.goodsDescription}
                    </Typography.Paragraph>
                  }
                />
                {tagListView(data.typeName)}
                <Flex justify="space-between" align="center">
                  <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                    {moment(data.createTime).fromNow()}
                  </Typography.Text>
                </Flex>
              </Card>
            </Link>
          </List.Item>
        )}
      />
    </PageContainer>
  );
};

export default IndexPage;
